package org.jpass.dc.view.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.jpass.dc.common.util.StringUtil;
import org.jpass.dc.view.common.BasicAction;

public class UploadFileAction extends BasicAction{

	@Override
	public void pause(String result) {
		// TODO Auto-generated method stub
		super.pause(result);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 4940347342576144823L;
	/* 上传的文件   */
	private File upload;
	/* 上传的文件名称   */
	private String uploadFileName;
	/* 上传的文件类型   */
	private String uploadContentType;
	/* 保存文件的相对路径  */
	private String savePath;

	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}


	/*@Override
	public String execute() throws Exception {
		PrintWriter out = this.getResponse().getWriter();
		if (StringUtil.isBlank(savePath)) {
			String msg = "Please select a path to save the upload file.";
			out.write("{success:false, msg: '"+msg+"', type:'warng'");
		} else if (StringUtil.isBlank(uploadFileName)) {
			String msg = "Please select a upload file.";
			out.write("{success:false, msg: '"+msg+"', type:'warng'");
		} else {
			uploadController(); // 开始接收上传文件
		}
		return Action.SUCCESS;
	}*/
	
	/**
	 * 上传文件
	 * @param src
	 * @param dst
	 */
	private  void copy(File src, File dst)  {
        try  {
           InputStream in = null ;
           OutputStream out = null ;
            try  {                
               in = new BufferedInputStream( new FileInputStream(src) );
               out = new BufferedOutputStream( new FileOutputStream(dst));
               byte [] buffer = new byte [in.available()];
               while (in.read(buffer) > 0 )  {
                  out.write(buffer);
              }                
            } finally  {
                if ( null != in)  {
                   in.close();
               } 
                 if ( null != out)  {
                   out.close();
               } 
           } 
        } catch (Exception e)  {
        	
           e.printStackTrace();
       } 
   }
	
	/**
	 * 上传控制文件
	 * @return
	 */
	public String uploadController() {
		try {
			HttpServletResponse response = this.getResponse();
			response.setContentType("text/html"); 
			PrintWriter out = response.getWriter();
			if (StringUtil.isBlank(savePath)) {
				String msg = "Please select a path to save the upload file.";
				out.write("{success:false, msg: '"+msg+"', type:'warng'");
			} else if (StringUtil.isBlank(uploadFileName)) {
				String msg = "Please select a upload file.";
				out.write("{success:false, msg: '"+msg+"', type:'warng'");
			} else {
				String uploadedFilePath = this.getUserRealWrokRootPath() + "/" 
						+ this.savePath + "/" + this.uploadFileName;
		        File uploadedFile = new File(uploadedFilePath);
		        if (uploadedFile.exists()) {
		        	out.write("{success:false, msg:'The file is exist.', type:'error'}");
		        } else {
		        	//因为内部类无法引用request，所以要实现一个。  
		        	/*@SuppressWarnings("unused")
					class MyProgressListener implements ProgressListener{  
		        	    private HttpServletRequest request = null;  
		        	    MyProgressListener(HttpServletRequest request){  
		        	        this.request = request;  
		        	    }  
		        	    public void update(long pBytesRead, long pContentLength, int pItems) {  
		        	        double percentage = ((double)pBytesRead/(double)pContentLength);  
		        	        //上传的进度保存到session，以便processController.jsp使用  
		        	        request.getSession().setAttribute("uploadPercentage", percentage);  
		        	    }  
		        	}*/

		        	copy(upload, uploadedFile);
		        	out.write("{success:true, msg:'Upload successful.'}");
		        	out.flush();
		        }
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	/**
	 * 上传进程控制
	 * @return
	 * @throws Exception 
	 */
	public String processController() throws Exception{
		HttpServletResponse response = this.getResponse();
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//从session取出uploadPercentage并送回浏览器  
		double d = (Double)this.getRequest().getSession().getAttribute("uploadPercentage");
		System.out.println(d);
		/*System.out.println(mon_obj);
		if (mon_obj != null) {
		    ProgressMonitor monitor = (ProgressMonitor)mon_obj;
		    d = ((double)monitor.getBytesRead()/(double)monitor.getBytesLength());
		}*/
	   
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+d+"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
	    String msg = "";
	    if(d<1){
	        //d<0代表正在上传，
	        msg = "正在上传文件...";
	        out.write("{success:true, msg: '"+msg+"', percentage:'" + d + "', finished: false}");
	    } else if(d>=1){
	        //d>1 代表上传已经结束
	        msg = "上传成功!";
	        this.getSession().remove("uploadPercentage");
	        out.write("{success:true, msg: '"+msg+"', percentage:1, finished:true}");
	        //注意返回的数据，success代表状态
	        //percentage是百分比
	        //finished代表整个过程是否结束。
	    }
	    this.getResponse().getWriter().flush();

		return NONE;
	}
}
